const { Client, LocalAuth, MessageMedia  } = require('whatsapp-web.js');
const schedule = require('node-schedule');
const qrcode_terminal = require('qrcode-terminal');
const qrcode = require('qrcode');
const util = require('util');
const fs = require('fs');
const path = require('path');
const axios = require('axios').default;
const erp_request = require('./erpauth').erp_request
const SendDingDingTextMsg = require('./erpauth').SendDingDingTextMsg
const SendDingDingMarkDownMsg = require('./erpauth').SendDingDingMarkDownMsg
const erpauth = require('./erpauth')
const uploadFileFromContent = require('./erpauth').uploadFileFromContent
const uploadFileToOSS = require('./erpauth').uploadFileToOSS
const express = require('express');

// 函数：获取可用的用户 ID 列表
function getAvailableUserIds() {
    const authDir = path.join(__dirname, '.wwebjs_auth');
    try {
        const dirs = fs.readdirSync(authDir);
        return dirs
            .filter(dir => dir.startsWith('session-client-'))
            .map(dir => dir.replace('session-client-', ''))
            .filter(id => id !== 'undefined');
    } catch (error) {
        console.error('读取 .wwebjs_auth 目录时出错:', error);
        return [];
    }
}

const userId = process.argv[2];
if (!userId) {
    const availableIds = getAvailableUserIds();
    console.error('错误: 未提供用户 ID。请提供用户 ID 作为第一个参数。');
    console.error('用法: node app.js <userId> [headless]');
    console.error('headless 参数可选，默认为 true（无头模式）。设置为 false 可禁用无头模式。');
    if (availableIds.length > 0) {
        console.error('\n可用的用户 ID:');
        availableIds.forEach(id => console.error(`- ${id}`));
    } else {
        console.error('\n没有找到可用的用户 ID。');
    }
    process.exit(1); // 退出程序，状态码 1 表示错误
}
const headless = process.argv[3] !== 'false'; // 第二个用户自定义参数，是否为无头模式
let client;
let restartClient = false;

const app = express();
app.use(express.json());
// 本地服务代码
// 直接在 app 上定义路由
app.post('/api/send-message', async (req, res) => {
    try {
        const { project_id, wc_id, messages } = req.body;
        const config = { project_id, wc_id };
        const results = [];

        if (!client) {
            throw new Error('WhatsApp client is not initialized');
        }

        for (const msg of messages) {
            try {
                let sentMessage;
                if (msg.url) {
                    const media = await MessageMedia.fromUrl(msg.url);
                    sentMessage = await client.sendMessage(msg._serialized, media, { caption: msg.body });
                } else {
                    sentMessage = await client.sendMessage(msg._serialized, msg.body);
                }

                // 标记消息为已发送
                await erp_request({
                    'project_id': config.project_id,
                    'wc_id': config.wc_id,
                    'id': msg.id
                }, 'wcsetsend', 'POST', 'crm/api/');

                console.log(`消息成功发送至 ${msg._serialized}`);

                // 同步消息内容
                const chat = await client.getChatById(msg._serialized);
                await sendMessageToServer(sentMessage, chat, config);

                results.push({ id: msg.id, status: 'success', message: '消息发送成功' });
            } catch (error) {
                console.error(`发送消息 ${msg.id} 时出错:`, error);
                results.push({ id: msg.id, status: 'error', message: error.message });
            }
        }

        res.json({ success: true, results });
    } catch (error) {
        console.error('处理发送消息请求时发生错误:', error);
        res.status(500).json({ success: false, error: error.message });
    }
});
//end
async function get_wc_config(_serialized) {
    const data = {
        _serialized: _serialized
    }
    console.log('get config of ' + _serialized)
    const response = await erp_request(data, 'wconfig', 'POST', 'crm/api/')
    // 如果返回失败，发钉钉消息提醒
    if (!response.success) {
        console.log('获取whatsapp配置失败')
        await SendDingDingTextMsg('获取whatsaspp ' + _serialized + '配置失败', hook=erpauth.dingding_hook,
            dingding_tag=erpauth.dingding_tag)
        return false
    }
    console.log('获取whatsapp配置成功')
    return response.data
}

async function get_unsend_messages(config) {
    //向服务器请求未发送的消息
    const response = await erp_request(config, 'wcunsend', 'POST', 'crm/api/')
    if(!response || !response.success) {
        //console.log('获取未发送消息失败')
        return false
    }
    // console.log('获取未发送消息:', response)
    if(response.refresh_chats) {
        for (let item of response.refresh_chats) {
            const chat = await client.getChatById(item._serialized)
            console.log('刷新聊天:', chat.name)
            await chat.sendSeen()
            // 向服务器返回
            console.log('发送设置need_refresh')
            console.log({'project_id': config.project_id, 'id': item.id, need_refresh: false})
            await erp_request({'project_id': config.project_id, 'id': item.id, need_refresh: false},
                'wcsetchat', 'POST', 'crm/api/')
            await SyncChatMessage(chat, config, true)
        }
    }
    return response.data
}

async function downloadImage(imageUrl, savePath) {
    try {
        const response = await axios({
            url: imageUrl,
            method: 'GET',
            responseType: 'stream'
        });

        const writer = fs.createWriteStream(savePath);

        response.data.pipe(writer);

        return new Promise((resolve, reject) => {
            writer.on('finish', resolve);
            writer.on('error', reject);
        });
    } catch (error) {
        console.error('下载图片时出错:', error);
    }
}
function getExtension(mimetype) {
    let extension = 'text'; // 默认扩展名，用于未知类型
    // 根据不同的MIME类型设置不同的文件扩展名
    if (mimetype.startsWith('image/')) {
        extension = mimetype.split('/')[1]; // 对于图像，直接使用MIME类型的扩展名
    } else if (mimetype.startsWith('video/')) {
        extension = 'mp4'; // 对于视频，默认设置为mp4
    } else if (mimetype.startsWith('audio/')) {
        // 对于音频，特殊检查opus格式
        if (mimetype.includes('opus')) {
            extension = 'opus';
        } else {
            extension = mimetype; // 其他音频格式使用MIME类型的扩展名
        }
    } else if (mimetype === 'application/pdf') {
        extension = 'pdf';
    } else if (mimetype === 'application/msword') {
        extension = 'doc';
    } else if (mimetype === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
        extension = 'docx';
    } else if (mimetype === 'application/vnd.ms-excel') {
        extension = 'xls';
    } else if (mimetype === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        extension = 'xlsx';
    } else if (mimetype === 'application/vnd.ms-powerpoint') {
        extension = 'ppt';
    } else if (mimetype === 'application/vnd.openxmlformats-officedocument.presentationml.presentation') {
        extension = 'pptx';
    } else if (mimetype === 'application/zip') {
        extension = 'zip';
    } else {
        extension = 'text';
    }
    return extension
}

// 根据id获取目录
function getFolderById(id) {
    const folder1 = id.substring(0, 1)
    const folder2 = id.substring(1, 2)
    const folder = folder1 + '/' + folder2
    const filepath = path.join('./cache/', 'messages', folder)
    if (!fs.existsSync(filepath)) {
        fs.mkdirSync(filepath, { recursive: true })
    }
    const filename = id + '.txt'
    return path.join(filepath, filename)
}

async function getProfilePicUrl(chatId) {
    console.log('头像URL: ' + chatId);
    let url = await client.getProfilePicUrl(chatId)
        .then(url => {
            if (url) {
                // console.log(`头像URL: ${url}`);
                // 使用_serialized + .jpeg作为文件名
                const savePath = path.join(__dirname, 'images/' + chatId + '.jpg'); // 保存图片的路径和文件名
                // 如果文件存在，不再下载
                if (fs.existsSync(savePath)) {
                    console.log('头像已经下载到:', savePath);
                    return url;
                }
                downloadImage(url, savePath)
                    .then(() => {
                        console.log('头像成功下载到:', savePath);
                    })
                    .catch(console.error);
                return url;
                // 这里你可以根据需要对头像URL进行操作，例如下载图片
            } else {
                console.log('该聊天没有设置头像。');
                return null;
            }
        })
        .catch(error => {
            console.error('获取头像时出错:', error);
            return null;
        });

    return url || '';
}

// 新增辅助函数来处理参与者信息
async function addParticipantInfo(serialized, participants) {
    if (!participants.find(p => p._serialized === serialized)) {
        try {
            const contact = await client.getContactById(serialized);
            participants.push({
                _serialized: contact.id._serialized,
                isMe: contact.isMe,
                name: contact.name,
                shortName: contact.shortName,
                pushname: contact.pushname,
                isBusiness: contact.isBusiness,
                number: contact.number
            });
        } catch (error) {
            console.error('Error getting contact:', error);
        }
    }
}

function processMessage(message, chat) {
    let messageTo = message.to;
    let messageFrom = message.author || message.from;

    // 如果消息没有 'to' 字段，使用聊天ID
    if (!messageTo) {
        messageTo = chat.id._serialized;
    }

    // 对于群组消息，接收者应该是群组ID
    if (chat.isGroup) {
        messageTo = chat.id._serialized;
    }

    // 只移除冒号及其后面的设备号部分，保留 @c.us 或 @g.us
    function removeDeviceId(id) {
        const parts = id.split('@');
        return parts[0].split(':')[0] + '@' + parts[1];
    }

    messageTo = removeDeviceId(messageTo);
    messageFrom = removeDeviceId(messageFrom);

    // 处理消息ID，去掉可能的设备号
    let messageId = message.id.id;
    if (messageId.includes('_')) {
        messageId = messageId.split('_')[0];
    }

    return {
        id_message: messageId,
        message_from: messageFrom,
        message_to: messageTo,
        hasMedia: message.hasMedia,
        body: message.body,
        timestamp: message.timestamp,
        links: message.links
    };
}

async function SyncChatMessage(chat, config, only_unread=false) {
    if(chat.id._serialized === '0@c.us') {
        console.log('跳过系统消息')
        return
    }
    console.log(`同步聊天: ${chat.name}`)
    // 打印chat所有属性
    // console.log(util.inspect(chat, {showHidden: false, depth: null}));
    console.log('头像URL: ' + chat.id._serialized)
    let url = await client.getProfilePicUrl(chat.id._serialized)
        .then(url => {
            if (url) {
                // console.log(`头像URL: ${url}`);
                return url
                // 使用_serialized + .jpeg作为文件名
                const savePath = path.join(__dirname, 'images/' + chat.id._serialized + '.jpg'); // 保存图片的路径和文件名
                // 如果文件存在，不再下载
                if (fs.existsSync(savePath)) {
                    console.log('头像已经下载到:', savePath);
                    return savePath
                }
                downloadImage(url, savePath)
                    .then(() => {
                        console.log('头像成功下载到:', savePath);
                    })
                    .catch(console.error);
                // 这里你可以根据需要对头像URL进行操作，例如下载图片
            } else {
                console.log('该聊天没有设置头像。');
                return null
            }
        })
        .catch(error => {
            console.error('获取头像时出错:', error);
        });
    if (url === null) {
        url = ''
    }
    const chatData = {
        whatsappconfig__serialized: client.info.me._serialized,
        _serialized: chat.id._serialized,
        name: chat.name,
        avatar: url,
        isGroup: chat.isGroup,
        timestamp: chat.timestamp,
        unreadCount: chat.unreadCount,
        project_id: config.project_id,
        participants: [],
        messages: []
    }
    if(chat.unreadCount) {
        console.log('有未读消息', chat.unreadCount)
    }
    // if(only_unread && chat.unreadCount === 0) {
    //     console.log('只同步未读消息，但是没有未读消息')
    //     let r = await erp_request(chatData, 'wcmessage', 'POST', 'crm/api/')
    //     return
    // }
    // console.log(chatData);
    // 对于每个聊天，获取其消息
    const media_messages = []
    const text_messages = []
    console.log('开始获取消息...')
    const messages = await chat.fetchMessages({limit: 50}); // 例如，这里限制为最新的10条消息
    for (let message of messages) {
        // 判断消息文件是否存在，存在就跳过
        const fullpath = getFolderById(message.id.id)
        if (fs.existsSync(fullpath)) {
            // console.log('已经获取过了')
            continue
        }
        const message_data = processMessage(message, chat)
         // 处理发送者信息
        await addParticipantInfo(message.from, chatData.participants);

        // 处理接收者信息
        await addParticipantInfo(message.to, chatData.participants);

        // 处理群组消息的特殊情况
        if (message.id.participant) {
            message_data.message_from = message.id.participant._serialized;
            await addParticipantInfo(message_data.message_from, chatData.participants);
        }
        if (message.hasMedia) {
            media_messages.push(message)
        } else {
            text_messages.push(message)
        }
        //console.log(message_data);
        chatData.messages.push(message_data)
        console.log('获取消息:', message.id.id)

    }
    // 将聊天数据同步到您的系统
    console.log('开始同步聊天到服务器...')
    //console.log(chatData)
    let r = await erp_request(chatData, 'wcmessage', 'POST', 'crm/api/')
    if (r && r.success) {
        console.log('成功同步聊天')
        // 保存textmessage的id到文件系统，避免下次重复上传
        const textmessage_ids = text_messages.map(m => m.id.id)
        //根据id的第一个字符和第二个字符作为文件夹名，避免文件夹内文件过多
        for (let id of textmessage_ids) {
            const fullpath = getFolderById(id)
            //创建文件
            fs.writeFile(fullpath, '', function (err) {
                if (err) {
                    console.log('创建文件失败')
                }
            })
        }
    }
    if (r && r.success && r.media_ids) {
        for (let message of media_messages) {
             // 如果id 不在 media_ids中，说明已经上传过了
            if (!r.media_ids.includes(message.id.id)) {
                continue
            }
            console.log('获取媒体文件:', message.id.id)
            message.downloadMedia().then(media => {
                // 处理下载完成后的媒体数据
                 if(media === undefined || media === null) {
                        console.log('获取媒体文件失败')
                        return
                    }

                    if(!media.data) {
                        return;
                    }
                    // 可以根据需要继续添加更多的MIME类型和对应的文件扩展名
                    // 如果mimetype不存在，使用text作为扩展名
                    let extension = 'text';
                    if(media.mimetype) {
                        extension = getExtension(media.mimetype);
                    }
                    let filename = message.id.id + '.' + extension;
                    const message_data = {
                        project_id: config.project_id,
                        _serialized: chat.id._serialized,
                        id_message: message.id.id,
                        content_type: media.mimetype,
                        filename: filename,
                        filesize: media.filesize
                    }
                    const mediaBuffer = Buffer.from(media.data, 'base64');
                    const targetpath = r.oss_path + filename
                    uploadFileToOSS(mediaBuffer, targetpath, config.oss_config).then( res => {
                        console.log('文件上传成功')
                        message_data.media_url = res.split('?')[0]
                        message_data.oss_path = targetpath
                        erp_request(message_data, 'wcmediamessage', 'POST', 'crm/api/')
                    })
            }).catch(error => {
                // 处理可能出现的错误
            });
            // const media = await message.downloadMedia();

        }
    } else {
        console.log('没有要获取的媒体文件')
    }
}


// 同步所有聊天
async function syncAllChats(only_unread=false) {
    // 获取所有聊天
    const config = await get_wc_config(client.info.me._serialized)
    const chats = await client.getChats();
    let chat_count = 0
    for (let chat of chats) {
        await SyncChatMessage(chat, config, only_unread)
        chat_count++
    }
    console.log('共同步了' + chat_count + '个聊天')
}

// 示例函数：将消息同步到您的系统
function syncMessageToYourSystem(message) {
    // 根据您的需要实现这个函数
    // 这可能包括将消息发送到您的服务器端API，或直接保存到数据库中
    console.log(`Syncing message to your system: ${message.body}`);
}

async function checkAndSendUnsentMessages(config) {
    let count = 0
    while (true) {
        try {
            const unsendMessages = await get_unsend_messages(config);
            if (unsendMessages && unsendMessages.length > 0) {
                for (const msg of unsendMessages) {
                    // 这里处理每条未发送的消息
                    // 例如，通过 client.sendMessage 发送消息
                    if(msg.url) {
                        const media = await MessageMedia.fromUrl(msg.url);
                        await client.sendMessage(msg._serialized, media, {caption: msg.body});
                    } else {
                        await client.sendMessage(msg._serialized, msg.body);
                    }

                    // 标记消息为已发送
                    await erp_request({'project_id': config.project_id,
                        'wc_id': config.wc_id, 'id': msg.id}, 'wcsetsend', 'POST', 'crm/api/');
                    console.log(`消息成功发送至 ${msg._serialized}`);
                    // 同步消消息内容
                    const chat = await client.getChatById(msg._serialized)
                    await SyncChatMessage(chat, config)
                }
            }
            // if(count % 10 === 0) {
            //     await syncAllChats(only_unread=true)
            // }
            count++
        } catch (error) {
            console.error('处理未发送消息时发生错误:', error);
            //退出程序重启
            restartClient = true
            console.error('5分钟后重启系统')
            break
        }
        // 等待一段时间再次检查，例如5秒
        await new Promise(resolve => setTimeout(resolve, 5000));
    }
}

// 创建一个异步函数来处理整个流程
async function generateAndUploadQRCode() {
    try {
        const tmpPath = './temp_qr_code.png'; // 临时保存二维码图片的路径
        const qrData = 'Some QR Code Data';
        const qr_filename = 'your_qr_code_name.png';
        const ossPath = '/temp/' + qr_filename; // 在OSS上保存的路径

        // 使用 Promise 包装 qrcode.toFile 以使用 async/await
        await util.promisify(qrcode.toFile)(tmpPath, qrData, { type: 'png' });
        console.log('二维码已生成并保存至', tmpPath);

        // 读取文件内容
        const content = fs.readFileSync(tmpPath);

        // 假设 uploadFileToOSS 已正确实现并返回 OSS URL
        const ossUrl = await uploadFileToOSS(content, ossPath, config.oss_config);
        console.log('二维码已上传到OSS:', ossUrl);

        // 发送钉钉 Markdown 消息
        const msg = `账号登录:${userId}\n请扫描二维码登录: ![QR Code](${ossUrl})`;
        await SendDingDingMarkDownMsg("登录whatsapp账号", msg, erpauth.dingding_hook, erpauth.dingding_tag);

        // 删除临时文件
        await unlinkAsync(tmpPath);
    } catch (error) {
        console.error('处理过程中出现错误:', error);
    }
}

async function handleMediaMessage(message, config, chatId) {
    try {
        const media = await message.downloadMedia();
        if (!media || !media.data) {
            console.log('获取媒体文件失败');
            return;
        }

        const extension = getExtension(media.mimetype);
        const filename = message.id.id + '.' + extension;
        const message_data = {
            project_id: config.project_id,
            _serialized: chatId,
            id_message: message.id.id,
            content_type: media.mimetype,
            filename: filename,
            filesize: media.filesize
        };

        const mediaBuffer = Buffer.from(media.data, 'base64');
        const targetpath = config.oss_path + filename;
        const res = await uploadFileToOSS(mediaBuffer, targetpath, config.oss_config);
        console.log('文件上传成功');
        message_data.media_url = res.split('?')[0];
        message_data.oss_path = targetpath;
        await erp_request(message_data, 'wcmediamessage', 'POST', 'crm/api/');
    } catch (error) {
        console.error('处理媒体消息时出错:', error);
    }
}

const sendMessageToServer = async (message, chat, config) => {
    const chatId = chat.id._serialized;
    let avatarUrl = '';

    console.log('头像URL: ' + chatId);
    try {
        avatarUrl = await client.getProfilePicUrl(chatId);
        if (avatarUrl) {
            const savePath = path.join(__dirname, 'images/' + chatId + '.jpg');
            if (fs.existsSync(savePath)) {
                console.log('头像已经下载到:', savePath);
            } else {
                await downloadImage(avatarUrl, savePath);
                console.log('头像成功下载到:', savePath);
            }
        } else {
            console.log('该聊天没有设置头像。');
        }
    } catch (error) {
        console.error('获取头像时出错:', error);
    }
    // 检查是否为群组消息
    if (message.author || message.from.includes('-')) {
        isGroup = true;
    }

    const chatData = {
        whatsappconfig__serialized: client.info.me._serialized,
        _serialized: chatId,
        name: chat.name,
        avatar: avatarUrl || '',
        isGroup: chat.isGroup,
        timestamp: message.timestamp,
        unreadCount: chat.unreadCount,
        project_id: config.project_id,
        participants: [],
        messages: []
    };
    chatData.messages.push(processMessage(message, chat))
    // 处理发送者信息
    await addParticipantInfo(message.from, chatData.participants);

    // 处理接收者信息
    await addParticipantInfo(message.to, chatData.participants);

    // 处理群组消息的特殊情况
    if (message.id.participant && message.id.participant._serialized) {
        chatData.messages[0].message_from = message.id.participant._serialized;
        await addParticipantInfo(chatData.messages[0].message_from, chatData.participants);
    }

    try {
        console.log('Sending message to server:', chatData);
        const response = await erp_request(chatData, 'wcmessage', 'POST', 'crm/api/');
        console.log('Message sent to server:', response);

        if (message.hasMedia) {
            await handleMediaMessage(message, config, chatId);
        }
    } catch (error) {
        console.error('Error sending message to server:', error);
    }
};

async function initializeClient() {
    const config = await get_wc_config(userId + '@c.us')
    console.log('get config success')
    client = new Client({
        authStrategy: new LocalAuth({
            clientId: `client-${userId}`
        }),
        puppeteer: {
            headless: headless,
            args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu']
        },
      //    webVersion: "2.2412.54",
      //   webVersionCache: {
      //   type: "remote",
      //   remotePath:
      //     "https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/2.2412.54.html",
      // }
    });
    //监听二维码事件,生成二维码，扫码登录,打印二维码
    client.on('qr', qr => {
        const qr_filename = userId + '_qr_code.png';
        const tmpPath = path.join(__dirname, 'images/' + qr_filename);
        // qrcode_terminal.generate(qr, {small: true});
        console.log(tmpPath)
        qrcode.toFile(tmpPath, qr, { type: 'png' }, async function (err) {
                if (err) throw err;
                console.log('二维码已生成并保存至', tmpPath);
                // 上传到OSS
                const content = fs.readFileSync(tmpPath);
                const ossPath = '/temp/' + qr_filename; // 在OSS上保存的路径

                try {
                    console.log(config.oss_config)
                    const ossUrl = await uploadFileToOSS(content, ossPath, config.oss_config);
                    console.log('二维码已上传到OSS:', ossUrl);

                    // 使用markdown格式发送钉钉消息
                    const msg = `账号登录:${userId}\n请扫描二维码登录: ![${ossUrl}](${ossUrl})`;
                    await SendDingDingMarkDownMsg("登录whatsapp账号", msg, erpauth.dingding_hook, erpauth.dingding_tag);

                    // 删除临时文件
                    fs.unlinkSync(tmpPath);
                } catch (error) {
                    console.error('上传二维码到OSS失败:', error);
                }
            });
    });
     console.log('正在初始化客户端...')
        client.on('loading_screen', (percent, message) => {
        console.log('LOADING SCREEN', percent, message);
        });

        client.on('authenticated', () => {
            console.log('AUTHENTICATED');
        });

        client.on('auth_failure', msg => {
            console.error('AUTHENTICATION FAILURE', msg);
        });

    client.on('message', message => {
        let lastActiveChatId = message.from;
        if (lastActiveChatId === client.info.me._serialized) {
            console.log('消息来自自己');
            lastActiveChatId = message.to;
        }
        console.log(`New Message from chat ID: ${lastActiveChatId}`);
        // 将消息同步到您的系统,获取chat对象
        client.getChatById(lastActiveChatId)
            .then(chat => {
                console.log(`找到会话: ${chat.name}`);
                sendMessageToServer(message, chat, config);
               //  console.log(client.info.me)
               //      get_wc_config(client.info.me._serialized).then(config => {
               //     SyncChatMessage(chat, config)
               // })
            })
            .catch(error => {
                console.error('获取会话时出错:', error);
            });
    });

    client.on('ready', async () => {
        console.log('Client is ready!');
        syncAllChats();
        const config = await get_wc_config(client.info.me._serialized);
        console.log(config)
        // 4小时同步一次
       schedule.scheduleJob('0 */4 * * *', function(){
            console.log('执行全局同步任务');
            syncAllChats().catch(console.error);
        });
        // 开始进入消息循环
        checkAndSendUnsentMessages(config);

    });

    client.initialize().catch(error => {
    console.error('Error initializing client:', error);
    });
}

// 启动 Express 服务器和 WhatsApp 客户端
// const PORT = process.env.PORT || 8080;
// app.listen(PORT, () => {
//     console.log(`Server is running on port ${PORT}`);
//     initializeClient().catch(error => {
//         console.error('初始化客户端时出错:', error);
//     });
// });

initializeClient().catch(error => {
    console.error('初始化客户端时出错:', error);
});
function checkClientStatus() {
    if (restartClient) {
        //关闭情况之前的client
        client.destroy();
        console.log('系统运行异常,重启系统');
        initializeClient();
    } else {
        console.log('客户端状态正常');
    }
}

// 设置定时器，例如每5分钟检查一次客户端状态
setInterval(checkClientStatus, 300000); // 300000 milliseconds = 5 minutes
